package com.xopencode.mvc;

import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mcb
 * @date 2022/3/27
 * @apiNote 自定义拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 进入控制器之前，放回false阻止进入控制器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 控制器执行完，进入jsp之前，可用于日志记录，敏感词过滤
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ModelMap modelMap = modelAndView.getModelMap();
        String word = modelMap.get("xxx").toString();
        if ("屏蔽词语".contains(word)){
            word.replace("替换词语",word);
            modelMap.put("xxx",word);
        }
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * jsp执行完成后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
